﻿using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Web;

namespace RepositoryPattern.Infrastructure
{
    public class Repository<T> : IRepository<T> where T : class
    {
        private AppDataContext _dataContext;
        private bool _isShareContext = false;

        public Repository()
        {
            _dataContext = new AppDataContext();
        }
        public Repository(AppDataContext context)
        {
            _dataContext = context;
            _isShareContext = true;
        }

        public DbSet<T> DbSet
        {
            get
            {
                return _dataContext.Set<T>();
            }
        }
        public virtual IQueryable<T> All()
        {
            return DbSet.AsQueryable();
        }

        public virtual IQueryable<T> Filter(System.Linq.Expressions.Expression<Func<T, bool>> filterExpression)
        {
            return DbSet.Where(filterExpression);
        }

        public void Dispose()
        {
            if (_isShareContext == false && _dataContext != null)
            {
                _dataContext.Dispose();
            }
        }

        public virtual T Create(T t)
        {
            return t;
        }
    }
}